/* (c)2010-2012 Andrea Caltroni (andrea.caltroni@pd.infn.it), INFN (www.infn.it)
 *
 * This file is part of the IGI Survey Portlet (from here on shortened to IGISP).
 * IGISP is free software: you can redistribute it and/or modify it 
 * under the terms of the GNU General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) any 
 * later version.
 *
 * IGISP is distributed in the hope that it will be useful, but WITHOUT ANY 
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with IGISP. If not, see <http://www.gnu.org/licenses/>.
 */
package it.infn.grid.liferay.survey.modules.admin.controller;

import it.infn.grid.liferay.survey.modules.admin.web.AnswersTypePropertyEditor;
import it.infn.grid.liferay.survey.modules.admin.web.ChangeQuestionOrderCommand;
import it.infn.grid.liferay.survey.modules.admin.web.ChangeQuestionOrderValidator;
import it.infn.grid.liferay.survey.modules.admin.web.SurveyPropertyEditor;

import java.util.ArrayList;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;

import org.ajm.spring.survey.modules.admin.model.AnswersType;
import org.ajm.spring.survey.modules.admin.model.Question;
import org.ajm.spring.survey.modules.admin.model.Survey;
import org.ajm.spring.survey.modules.admin.service.QuestionService;
import org.ajm.spring.survey.modules.admin.service.SurveyService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.portlet.bind.PortletRequestDataBinder;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;

/**
 * The controller for the change question order operation on the list of Questions
 * of a Survey.
 * 
 * @author Andrea Caltroni, andrea.caltroni@pd.infn.it, INFN
 */
@RequestMapping(value="VIEW")
@Controller(value="changeQuestionOrderController")
public class ChangeQuestionOrderController {

    // ------------------------------------------------------------------------|
    // --- CONSTANTS ----------------------------------------------------------|
    // ------------------------------------------------------------------------|

    // --- CLASS VARIABLES ----------------------------------------------------|
    // ------------------------------------------------------------------------|
    // ------------------------------------------------------------------------|

    static Logger logger = Logger.getLogger(ChangeQuestionOrderController.class);
    
    // ------------------------------------------------------------------------|
    // --- INSTANCE VARIABLES -------------------------------------------------|
    // ------------------------------------------------------------------------|

    @Autowired
    @Qualifier("surveyService")
    private SurveyService surveyService;
    
    @Autowired
    @Qualifier("questionService")
    private QuestionService questionService;
    
    @Autowired
    @Qualifier("changeQuestionOrderValidator")
    private ChangeQuestionOrderValidator changeQuestionOrderValidator;
    
    // ------------------------------------------------------------------------|
    // --- CONSTRUCTORS -------------------------------------------------------|
    // ------------------------------------------------------------------------|

    // ------------------------------------------------------------------------|
    // --- CLASS METHODS ------------------------------------------------------|
    // ------------------------------------------------------------------------|

    // ------------------------------------------------------------------------|
    // --- INSTANCE METHODS ---------------------------------------------------|
    // ------------------------------------------------------------------------|

    /**
     * Setup binder for adding/editing surveys.
     */
    @InitBinder("changeQuestionOrderCommand")
    protected void initBinder(PortletRequestDataBinder binder) {
        
        binder.registerCustomEditor(Survey.class, new SurveyPropertyEditor(surveyService));
        binder.registerCustomEditor(AnswersType.class, new AnswersTypePropertyEditor());
    }

    // ------------------------------------------------------------------------|

    @ModelAttribute("changeQuestionOrderCommand")
    public ChangeQuestionOrderCommand getCommandObject(@RequestParam("surveyID") Long surveyId) {
        
        Survey survey = getSurveyService().findById(surveyId);
        ChangeQuestionOrderCommand command = new ChangeQuestionOrderCommand(getSurveyService().findQuestions(survey));
        return command;
    }

    // ------------------------------------------------------------------------|

    /**
     * Edits the order of a survey's questions. Render phase.
     * 
     * @param surveyId 
     * @param model 
     * @return The attribute in the model defining the action of editing a question.
     */
    @RenderMapping(params="action=showChangeQuestionOrderForm")
    public String showChangeQuestionOrderForm(@RequestParam("surveyID") Long surveyId, Model model) {
        
        Survey survey = getSurveyService().findById(surveyId);
        model.addAttribute("survey", survey);
        // find valid position range for questions (1 is the lower value)
        Question highestPosQuestion = getSurveyService().findHighestPositionQuestion(survey);
        List<Integer> questionPositions = new ArrayList<Integer>();
        for (int pos = 1; pos <= highestPosQuestion.getPosition(); pos++) {
            questionPositions.add(pos);
        }
        model.addAttribute("questionPositions", questionPositions);
            
        return "questionOrderChange";
    }

    // ------------------------------------------------------------------------|
    
    /**
     * Saves the edited order of the questions of a survey after validating it. 
     * Action phase.
     * 
     * @param request 
     * @param response 
     * @param chQsOrderCommand
     * @param result 
     * @param sessionStatus 
     */
    @ActionMapping(params="action=changeQuestionOrder")
    public void submitchangeQuestionOrderForm(ActionRequest request, ActionResponse response,
            @ModelAttribute("changeQuestionOrderCommand") ChangeQuestionOrderCommand chQsOrderCommand, BindingResult result, SessionStatus sessionStatus) {

        getChangeQuestionOrderValidator().validate(chQsOrderCommand, result);
        
        if (!result.hasErrors()) {
            List<Question> questionsList = new ArrayList<Question>();
            questionsList.addAll(chQsOrderCommand.getQuestions());
            for (Question question: chQsOrderCommand.getQuestions()) {
                questionService.save(question);
            }
            
            response.setRenderParameter("action", "viewSurveyQuestions");
            response.setRenderParameter("surveyID", chQsOrderCommand.getQuestions().first().getSurvey().getId().toString());
        }
        else {
            if (logger.isDebugEnabled()) {
                for (ObjectError error: result.getAllErrors()) {
                    logger.debug("Change question order form reported [" + error.toString() + "]");
                }
            }
            response.setRenderParameter("action", "showChangeQuestionOrderForm");
            response.setRenderParameter("surveyID", chQsOrderCommand.getQuestions().first().getSurvey().getId().toString());
        }
        
        sessionStatus.setComplete();
    }

    // --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --|
    // ---[  GETTERS AND SETTERS  ]--------------------------------------------|
    // --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --|

    /**
     * @return the surveyService
     */
    public SurveyService getSurveyService() {
        return surveyService;
    }

    // ------------------------------------------------------------------------|

    /**
     * @param surveyService the surveyService to set
     */
    public void setSurveyService(SurveyService surveyService) {
        this.surveyService = surveyService;
    }

    // ------------------------------------------------------------------------|

    /**
     * @return the questionService
     */
    public QuestionService getQuestionService() {
        return questionService;
    }

    // ------------------------------------------------------------------------|

    /**
     * @param questionService the questionService to set
     */
    public void setQuestionService(QuestionService questionService) {
        this.questionService = questionService;
    }

    // ------------------------------------------------------------------------|
    
    /**
     * @return the changeQuestionOrderValidator
     */
    public ChangeQuestionOrderValidator getChangeQuestionOrderValidator() {
        return changeQuestionOrderValidator;
    }

    // ------------------------------------------------------------------------|

}
